﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Polaris.Common;
using Polaris.Domain.Model.Entity.Exception;
using StackExchange.Redis;

namespace Polaris.WebApi.Controllers.Admin
{
    /// <summary>
    /// 文件处理控制器
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class FileController : BaseController
    {
        private readonly object _locker = new object();

        /// <summary>
        /// 上传图片到文件夹
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult UploadImageFile(IFormFile file)
        {
            try
            {
                lock (_locker)
                {
                    if (file != null && file.Length > 0)
                    {
                        //生成文件名
                        string fileName = Guid.NewGuid().ToString() + Path.GetExtension(file.FileName);
                        // 获取文件保存路径，确保是在根目录下
                        string rootPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "ImageFile");
                        string filePath = Path.Combine(rootPath, fileName);
                        // 获取文件夹路径
                        string directoryPath = Path.GetDirectoryName(filePath);

                        // 检查目录是否存在，如果不存在，则创建目录
                        if (!Directory.Exists(directoryPath))
                        {
                            Directory.CreateDirectory(directoryPath);
                        }
                        using (var stream = new FileStream(filePath, FileMode.Create))
                        {
                            //将文件复制到路径
                            file.CopyTo(stream);
                        }
                        return SUCCESS($"ImageFile/{fileName}");
                    }
                    else
                    {
                        return SUCCESS("文件为空");
                    }
                }
            }
            catch (Exception ex)
            {
                throw new CustomException(Domain.Model.Enum.ResultCode.FAIL, ex.Message);
            }
        }
    }
}
